import React, { useEffect } from 'react'
import RootWithIntl from './RootWithIntl'
import { connectFor } from '@folio/stripes-connect'
import { isRoot, appModules, modules, dynamicAppsUrl } from 'stripes-config'
import { registerMicroApps, start } from 'qiankun'
import { useGlobalDispatch, useGlobalState } from '@jiatuan/hooks'

function WithRoot(props) {
    const connect = connectFor('@folio/core', props.stripes.epics, props.stripes.logger)
    const stripes = props.stripes.clone({ connect })
    const globalDispatch = useGlobalDispatch()
    const globalState = useGlobalState()

    const isMainApp = () => {
        return isRoot && !window.__POWERED_BY_QIANKUN__;
    }

    const genCommonProps = () => {
        const [basic] = modules.app;
        return {
            globalStore: props.store,
            stripes,
            ...basic.getModule(),
        }
    }

    const fetchApps = async () => {
        try {
            const res = await fetch(dynamicAppsUrl, {
                headers: {
                    'X-Okapi-tenant': stripes.okapi.tenant,
                    'X-Okapi-token': props.token,
                }
            })
            const { data } = await res.json();
            return data;
        } catch (error) {
            return [];
        }
    }

    const getMicroApps = async () => {
        const apps = await fetchApps()

        return (apps || []).filter(item => {
            if (item?.hasOwnProperty?.('children')) {
                const perm = item.appCode;
                if (props.stripes.hasPerm(perm)) {
                    const [_, appName] = item?.appCode?.split('.') || []
                    const activeRule = '/' + appName;
                    Object.assign(item, {
                        container: '#content',
                        name: appName,
                        entry: item.accessUrl,
                        activeRule,
                        props: {
                            activeRule,
                            appInfo: item,
                            ...(item.props || {}),
                            ...genCommonProps()
                        }
                    });
                    return true;
                }
                return false;
            } else {
                const perm = `module.${item.appRoute}.enabled`;
                if (props.stripes.hasPerm(perm)) {
                    const activeRule = '/' + item.appRoute;
                    Object.assign(item, {
                        container: '#content',
                        name: item.appRoute,
                        entry: item.accessUrl,
                        activeRule,
                        props: {
                            activeRule,
                            appInfo: item,
                            ...(item.props || {}),
                            ...genCommonProps()
                        }
                    });
                    return true;
                }
                return false;
            }
        });
    }

    const getMicroApps2 = () => {
        return (appModules || []).filter(item => {
            const perm = `module.${item.name}.enabled`;
            if (props.stripes.hasPerm(perm)) {
                const activeRule = '/' + item.name;
                Object.assign(item, {
                    container: '#content',
                    activeRule,
                    props: {
                        activeRule,
                        ...(item.props || {}),
                        ...genCommonProps()
                    }
                });
                return true;
            }
            return false;
        });
    }

    useEffect(() => {
        async function main() {
            if (isMainApp() && props.token) {
                const apps2 = getMicroApps2() // for test
                const apps = await getMicroApps();
                globalDispatch({
                    type: 'setApps',
                    payload: {
                      apps
                    }
                })

                registerMicroApps(apps);
                start();
            }
        }
        main()
    }, [])

    return <RootWithIntl {...props} />
}

export default WithRoot
